package cn.portx.listener;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.persistence.Column;

import com.bstek.dorado.data.listener.GenericObjectListener;
import com.bstek.dorado.data.type.EntityDataType;
import com.bstek.dorado.data.type.property.PropertyDef;
import com.bstek.dorado.data.type.validator.Validator;
import com.bstek.dorado.view.type.property.validator.CharLengthValidator;

import cn.portx.entity.BaseEntity;

public class EntityDataTypeGenericObjectListener extends GenericObjectListener<EntityDataType> {

	@Override
	public boolean beforeInit(EntityDataType object) throws Exception {
		return true;
	}

	@Override
	public void onInit(EntityDataType dataType) throws Exception {
		Class<?> clazz = dataType.getCreationType();
		if (clazz != null && BaseEntity.class.isAssignableFrom(clazz)) {
			Map<String, PropertyDef> map = dataType.getPropertyDefs();
			for (String fieldName : map.keySet()) {
				PropertyDef pd = map.get(fieldName);
				Field field = null;
				try {
					field = clazz.getDeclaredField(fieldName);
				} catch (Exception e) {
					continue;
				}
				if (String.class.isAssignableFrom(field.getType())) {
					Column column = field.getAnnotation(Column.class);
					if (column != null) {
						int length = column.length();
						List<Validator> validators = pd.getValidators();
						if (validators == null) {
							validators = new ArrayList<Validator>();
						}
						
						for(Iterator<Validator> iter = validators.iterator();iter.hasNext();){
							Validator v = iter.next();
							if (v instanceof CharLengthValidator) {
								iter.remove();
							}
						}
						
						boolean found = false;
//						for (Validator v : validators) {
//							if (v instanceof CharLengthValidator) {
//								found = true;
//								break;
//							}
//						}
						if (!found) {
							CharLengthValidator v = new CharLengthValidator();
							v.setMaxLength(length);
							v.setResultMessage(pd.getLabel() + "不能超过" + length / 2 + "个汉字或" + length + "个英文字符！");
							validators.add(v);
						}
						pd.setValidators(validators);
					}
				}

			}
		}
	}

}
